<style scoped lang="scss">
$primary: #3498db;
$info: #4299e1;
$warning: #ed8936;
$danger: #e53e3e;
$success: #38a169;
$text-primary: #2d3748;
$text-secondary: #718096;

.user-detail-page {
  padding: 24px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 80px);
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: white;
  padding: 20px 24px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.04);
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.back-link {
  color: $text-secondary;
  text-decoration: none;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
}

.back-link:hover {
  color: $primary;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.btn-edit {
  background-color: $warning;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-edit:hover {
  background-color: darken($warning, 10%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(237, 137, 54, 0.3);
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.04);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(52, 152, 219, 0.1);
  border-radius: 50%;
  border-top-color: $primary;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 信息卡片 */
.info-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.04);
  overflow: hidden;
  margin-bottom: 24px;
}

.user-info-header {
  display: flex;
  padding: 24px;
  gap: 24px;
  border-bottom: 1px solid #edf2f7;
}

.user-avatar-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.user-avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  box-shadow: 0 4px 14px rgba(0, 0, 0, 0.1);
  border: 3px solid white;
}

.basic-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.basic-info h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: $text-primary;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.label {
  color: $text-secondary;
  font-weight: 500;
}

.user-role-tag {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  letter-spacing: 0.2px;
}

.user-role-tag.agent {
  background-color: #ebf8ff;
  color: #3182ce;
}

.user-role-tag.distributor {
  background-color: #f0fff4;
  color: #38a169;
}

.user-role-tag.normal {
  background-color: #f7fafc;
  color: #718096;
}

.status-tag {
  display: inline-flex;
  align-items: center;
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  letter-spacing: 0.2px;
}

.status-tag.active {
  background-color: #f0fff4;
  color: #38a169;
}

.status-tag.active::before {
  content: '';
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #38a169;
  margin-right: 6px;
}

.status-tag.inactive {
  background-color: #fff5f5;
  color: #e53e3e;
}

.status-tag.inactive::before {
  content: '';
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #e53e3e;
  margin-right: 6px;
}

.commission-rate {
  font-weight: 600;
  color: $primary;
}

.user-info-details {
  padding: 24px;
}

.info-section {
  margin-bottom: 32px;
}

.info-section h3 {
  font-size: 18px;
  font-weight: 600;
  color: $text-primary;
  margin: 0 0 16px 0;
  position: relative;
  padding-left: 14px;
}

.info-section h3::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: $primary;
  border-radius: 2px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

/* 销售业绩统计卡片 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.stat-card {
  background-color: #f8fafc;
  border-radius: 12px;
  padding: 20px;
  position: relative;
  transition: all 0.3s;
  border: 1px solid #edf2f7;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: $text-primary;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: $text-secondary;
  font-weight: 500;
}

.stat-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 20px;
  color: rgba(66, 153, 225, 0.2);
}

.money {
  font-family: 'SF Mono', 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
  font-weight: 600;
  color: #2d3748;
}

/* 经销商表格 */
.distributor-table-container {
  margin-top: 16px;
  overflow-x: auto;
}

.distributor-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
}

.distributor-table th,
.distributor-table td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #edf2f7;
}

.distributor-table th {
  font-weight: 600;
  color: $text-secondary;
  background-color: #f7fafc;
  font-size: 13px;
}

.distributor-table tbody tr:hover {
  background-color: #f8fafc;
}

.distributor-table tfoot {
  font-weight: 600;
}

.text-right {
  text-align: right;
}

/* 备注信息 */
.remark-box {
  background-color: #f8fafc;
  border-radius: 8px;
  padding: 16px;
  color: $text-secondary;
  border: 1px solid #edf2f7;
  white-space: pre-line;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-info-header {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .basic-info {
    align-items: center;
  }

  .info-item {
    justify-content: center;
  }

  .stats-grid {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  }

  .stat-value {
    font-size: 22px;
  }
}

.chart-wrapper {
  width: 100%;
  height: auto;
  min-height: 450px;
}

.section-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 16px;
  color: var(--el-text-color-primary);
}

.user-sales-container {
  margin-top: 20px;
}

.user-commission {
  margin-top: 20px;
}

.user-orders {
  margin-top: 20px;
}
</style>

<template>
  <div class="user-detail-page">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="header-left">
        <router-link to="/admin/users" class="back-link">
          <i class="fas fa-arrow-left"></i> 返回用户列表
        </router-link>
        <h1>{{ userData?.user || '用户详情' }} <span class="user-role-tag" :class="roleClass">{{ userData?.role }}</span></h1>
      </div>
      <!-- <div class="header-actions">
        <button class="btn-edit" @click="handleEdit">
          <i class="fas fa-edit"></i> 编辑
        </button>
      </div> -->
    </div>

    <!-- 加载中提示 -->
    <div class="loading-container" v-if="loading">
      <div class="loading-spinner"></div>
      <p>加载用户数据中...</p>
    </div>

    <!-- 用户基本信息卡片 -->
    <div class="info-card" v-if="!loading && userData">
      <div class="user-info-header">
        <!-- <div class="user-avatar-container">
          <img :src="userData.avatar" alt="用户头像" class="user-avatar" />
        </div> -->

        <div class="basic-info">
          <h2>{{ userData.name }}</h2>

          <!-- <div class="info-item">
            <span class="label">账户类型：</span>
            <span class="user-role-tag" :class="roleClass">{{ userData.role }}</span>
          </div> -->

          <div class="info-item">
            <span class="label">创建时间：</span>
            <span>{{ userData.create_time }}</span>
          </div>

          <div class="info-item">
            <span class="label">状态：</span>
            <template v-for="(item, index) in userStatus" :key="index">
              <span
                class="status-tag"
                v-if="userData.status == item.value"
                :class="{
                  'active': userData.status == item.value,
                  'inactive': userData.status != item.value
                }">
                {{ item.label }}
              </span>
            </template>
          </div>

          <div class="info-item" v-if="isAgentOrDistributor">
            <span class="label">{{ userData.role === '区域代理' ? '返点比例' : '佣金比例' }}：</span>
            <span class="commission-rate">{{ userData.commissionRate }}%</span>
          </div>
        </div>
      </div>

      <div class="user-info-details">
        <div class="info-section">
          <h3>联系信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">手机号码：</span>
              <span>{{ formatPhone(userData.phone) }}</span>
            </div>
            <div class="info-item">
              <span class="label">电子邮箱：</span>
              <span>{{ userData.email }}</span>
            </div>
            <!-- <div class="info-item">
              <span class="label">联系地址：</span>
              <span>{{ userData.address || '未设置' }}</span>
            </div> -->
            <!-- <div class="info-item">
              <span class="label">最后登录：</span>
              <span>{{ userData.lastLoginTime || '未记录' }}</span>
            </div> -->
          </div>
        </div>

        <!-- 分销商和区域代理的销售业绩信息 -->
        <div class="info-section" v-if="isAgentOrDistributor">
          <h3>销售业绩</h3>
          <div class="stats-grid">
            <div class="stat-card">
              <div class="stat-value money">{{ formatMoney(userData.totalSales) }}</div>
              <div class="stat-label">累计销售额</div>
              <i class="stat-icon fas fa-shopping-cart"></i>
            </div>
            <div class="stat-card">
              <div class="stat-value">{{ userData.totalOrders || 0 }}</div>
              <div class="stat-label">累计订单数</div>
              <i class="stat-icon fas fa-receipt"></i>
            </div>
            <div class="stat-card">
              <div class="stat-value money">{{ formatMoney(userData.totalCommission) }}</div>
              <div class="stat-label">累计佣金</div>
              <i class="stat-icon fas fa-money-bill-wave"></i>
            </div>
            <div class="stat-card">
              <div class="stat-value money">{{ formatMoney(userData.walletBalance) }}</div>
              <div class="stat-label">待结算佣金</div>
              <i class="stat-icon fas fa-wallet"></i>
            </div>
            <div class="stat-card">
              <div class="stat-value money">{{ formatMoney(userData.withdrawAmount) }}</div>
              <div class="stat-label">已提现佣金</div>
              <i class="stat-icon fas fa-hand-holding-usd"></i>
            </div>
          </div>
        </div>

        <!-- 销售数据图表 - 仅为分销商和区域代理显示 -->
        <div class="info-section" v-if="isAgentOrDistributor && !loading && userData">
          <h3>销售数据趋势</h3>
          <div class="chart-wrapper">
            <UserSalesChart
              :userId="userId"
              :title="userData.role === '区域代理' ? '区域代理销售数据' : '分销商销售数据'"
              ref="salesChartRef"
            />
          </div>
        </div>

        <!-- 佣金记录区域 - 仅为分销商和区域代理显示 -->
        <div class="info-section" v-if="isAgentOrDistributor && !loading && userData">
          <h3>佣金记录</h3>
          <div class="commission-records-wrapper">
            <UserCommissionRecords
              :userId="userId"
            />
          </div>
        </div>

        <!-- 用户订单列表 -->
        <div class="info-section">
          <h3>用户订单列表</h3>
          <div class="orders-list-wrapper">
            <UserOrdersList
              :userId="userId"
              :isDistributorOrAgent="isAgentOrDistributor"
            />
          </div>
        </div>

        <!-- 区域代理的经销商信息 -->
        <div class="info-section" v-if="userData.role === '区域代理' && userData.distributors && userData.distributors.length > 0">
          <h3>旗下经销商 ({{ userData.distributorCount }})</h3>
          <div class="distributor-table-container">
            <table class="distributor-table">
              <thead>
                <tr>
                  <th>经销商名称</th>
                  <th>联系电话</th>
                  <th>销售额</th>
                  <th>佣金比例</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(distributor, index) in userData.distributors" :key="index">
                  <td>{{ distributor.name }}</td>
                  <td>{{ formatPhone(distributor.phone) }}</td>
                  <td class="money">{{ formatMoney(distributor.sales) }}</td>
                  <td>{{ distributor.commissionRate }}%</td>
                </tr>
              </tbody>
              <tfoot>
                <tr>
                  <td colspan="2" class="text-right">总计：</td>
                  <td class="money">{{ formatMoney(userData.distributorTotalSales) }}</td>
                  <td></td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>

        <!-- 备注信息 -->
        <div class="info-section" v-if="userData.remark">
          <h3>备注信息</h3>
          <div class="remark-box">
            {{ userData.remark }}
          </div>
        </div>
      </div>
    </div>

    <!-- 用户编辑模态框 -->
    <UserFormModal
      v-if="showEditModal"
      :visible="showEditModal"
      :is-edit="true"
      :user-data="formUserData"
      @close="closeEditModal"
      @submit="saveUser"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { generateUserDetailData } from '@/utils/adminMock';
// @ts-ignore - 忽略组件类型检查错误
import UserFormModal from '@/components/admin/users/UserFormModal.vue';
// @ts-ignore - 忽略组件类型检查错误
import UserSalesChart from '@/components/admin/users/UserSalesChart.vue';
// @ts-ignore - 忽略组件类型检查错误
import UserOrdersList from '@/components/admin/users/UserOrdersList.vue';
// @ts-ignore - 忽略组件类型检查错误
import UserCommissionRecords from '@/components/admin/users/UserCommissionRecords.vue';
import { GetUserDetailsApi } from '@/api/index'

const userStatus = [
  {
    label: '冻结',
    value: 0,
    type: 'error'
  },
  {
    label: '正常',
    value: 1,
    type: 'success'
  }
]

const route = useRoute();

const router = useRouter();

const userId = computed(() => route.params.userId as string);

// 状态变量
const userData = ref<any>(null);
const loading = ref(true);
const showEditModal = ref(false);
const formUserData = ref<any>({});

// 获取用户数据
const fetchUserData = async () => {
  loading.value = true;
  try {
    // 在实际项目中，这里应该调用API获取用户数据
    // 这里使用adminMock中的函数生成模拟数据
    const data = await GetUserDetailsApi({id: userId.value});

    console.log(789789, data)

    userData.value = data.data;
  } catch (error) {
    console.error('获取用户数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 监听路由参数变化，重新获取数据
watch(() => route.params.userId, () => {
  fetchUserData();
});

// 页面加载时获取数据
onMounted(() => {
  fetchUserData();
});

// 计算属性：是否为分销商或区域代理
const isAgentOrDistributor = computed(() => {
  if (!userData.value) return false;
  return userData.value.role === '区域代理' || userData.value.role === '分销商';
});

// 计算属性：是否为分销商
const isDistributor = computed(() => {
  if (!userData.value) return false;
  return userData.value.role === '分销商';
});

// 计算属性：是否为区域代理
const isRegionalAgent = computed(() => {
  if (!userData.value) return false;
  return userData.value.role === '区域代理';
});

// 计算属性：用户角色样式类
const roleClass = computed(() => {
  if (!userData.value) return '';
  const role = userData.value.role;
  if (role === '区域代理') return 'agent';
  if (role === '分销商') return 'distributor';
  return 'normal';
});

// 格式化电话号码
const formatPhone = (phone: string | undefined) => {
  if (!phone) return '';
  return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3');
};

// 格式化金额
const formatMoney = (amount: number | null | undefined) => {
  if (amount === null || amount === undefined) return '¥0.00';
  return amount.toLocaleString('zh-CN', { style: 'currency', currency: 'CNY' });
};

// 编辑用户
const handleEdit = () => {
  if (!userData.value) return;

  // 转换数据格式为UserFormModal期望的格式
  formUserData.value = {
    id: userData.value.id,
    name: userData.value.name,
    role: userData.value.role === '区域代理' ? 'agent' : userData.value.role === '分销商' ? 'distributor' : 'normal',
    phone: userData.value.phone,
    email: userData.value.email,
    avatar: userData.value.avatar,
    status: userData.value.status,
    commissionRate: userData.value.commissionRate || 0,
    walletBalance: userData.value.walletBalance || 0,
    withdrawAmount: userData.value.withdrawAmount || 0,
    createTime: userData.value.createTime,
    address: userData.value.address,
    totalSales: userData.value.totalSales,
    totalCommission: userData.value.totalCommission,
    distributors: userData.value.distributors || [],
    distributorCount: userData.value.distributorCount || 0,
    distributorTotalSales: userData.value.distributorTotalSales || 0,
    remark: userData.value.remark || ''
  };

  showEditModal.value = true;
};

// 关闭编辑模态框
const closeEditModal = () => {
  showEditModal.value = false;
};

// 保存用户
const saveUser = (formData: any) => {
  // 转换用户类型为中文显示
  const roleMap: Record<string, string> = {
    'agent': '区域代理',
    'distributor': '分销商',
    'normal': '普通用户'
  };

  // 更新用户数据
  userData.value = {
    ...userData.value,
    name: formData.username,
    role: roleMap[formData.role],
    phone: formData.phone,
    email: formData.email,
    avatar: formData.avatar,
    status: formData.status,
    commissionRate: formData.commissionRate,
    walletBalance: formData.walletBalance || 0,
    withdrawAmount: formData.withdrawAmount || 0,
    address: formData.address || '',
    distributors: formData.distributors || [],
    distributorCount: formData.distributorCount || 0,
    distributorTotalSales: formData.distributorTotalSales || 0,
    remark: formData.remark
  };

  // 关闭模态框
  closeEditModal();

  // 显示成功消息（在实际项目中，这里可以使用Toast或者其他通知组件）
  setTimeout(() => {
    alert('用户更新成功！');
  }, 300);
};

const showUserOrders = computed(() => {
  return userData.value && (isDistributor.value || isRegionalAgent.value || userData.value.role === 'merchant');
});

const showUserCommission = computed(() => {
  return userData.value && (isDistributor.value || isRegionalAgent.value);
});
</script>
